package com.mgq.netty.chat.handler;

import com.mgq.netty.chat.message.RpcRequestMessage;
import com.mgq.netty.chat.message.RpcResponseMessage;
import com.mgq.netty.chat.service.ServiceFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

@Slf4j
@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) throws Exception {
        RpcResponseMessage responseMessage = new RpcResponseMessage();
        responseMessage.setSequenceId(msg.getSequenceId());
        try {
            //通过反射调用对应的方法,将方法返回值传给客户端
            String interfaceName = msg.getInterfaceName();
            Class<?> aClass = Class.forName(interfaceName);
            Object service = ServiceFactory.getService(aClass);
            Method method = service.getClass().getMethod(msg.getMethodName(), msg.getParamType());
            Object value = method.invoke(service, msg.getParamValue());
            responseMessage.setReturnValue(value);
        } catch (Exception e) {
            log.error("方法调用出现异常",e);
            //服务端不要将完整的异常抛给客户端,应该只把重要的信息给客户端
            String message = e.getCause().getMessage();
            //e.getCause()和e.getMessage()原因, cause是具体的什么引起的.e.getMessage 只会获得具体的异常名称.
            responseMessage.setExceptionValue(new Exception("远程调用出错"+message));
        }
        ctx.writeAndFlush(responseMessage);
    }
}
